import { _decorator, Component, instantiate, math, Node, Prefab } from 'cc';
import { Pipe } from './Pipe';
const { ccclass, property } = _decorator;

@ccclass('PipeSpawner')
export class PipeSpawner extends Component {
    @property(Prefab)
    pipePrefab: Prefab = null

    @property
    spawnRate: number = 1.5

    private _timer: number = 0
    private _isSpawning: boolean = false
    // start() {

    // }

    update(deltaTime: number) {
        if(!this._isSpawning)return;
        this._timer += deltaTime;
        if(this._timer > this.spawnRate){
            this._timer = 0
            const pipeInst = instantiate(this.pipePrefab)
            this.node.addChild(pipeInst)
            const p = this.node.getWorldPosition()
            pipeInst.setWorldPosition(p)
            const y = math.randomRangeInt(-100, 200)
            
            const pLocal = pipeInst.getPosition()
            pipeInst.setPosition(pLocal.x, y)
        }
    }

    public pause(){
        this._isSpawning = false

        this.node.children.forEach(cNode=>{
            const pipe = cNode.getComponent(Pipe)
            if(pipe){
                pipe.enabled = false
            }
        })
    }
    public generate(){
        this._isSpawning = true
    }
}

